ActiveAdmin.register_page "LimitDashboard" do
  menu priority: 30, label: '涨停看板'

  content title: "" do
    div class: "blank_slate_container" do
      span class: "blank_slate" do
        h3 "高标：连板数量大于5【没有，说明市场炒作题材乱，没有明确的主线，炒作概念不持续】"
        h3 "高标：观察连板2、3可能点燃一个概念，结合  ths:choice_block 选出板块，然后再选择板块强势股： ths:block_stock"
        span "高标走势: 高标涨幅大，说明市场情绪高，做强势概念"
      end
    end
    redis_stocks = Parallel.map(Stock.all, in_processes: 4, progress: false) do |stock|
      JSON.parse $Redis.get(stock.symbol) unless $Redis.get(stock.symbol).nil?
    end

    last_cal_date = LimitList.last_cal_date # 当前交易日期
    last_pretrade_date = LimitList.last_pretrade_date # 上一交易日期
    today_limit_time_max = last_cal_date.pluck(:limit_times).max
    yesterday_limit_time_max = last_pretrade_date.pluck(:limit_times).max

    all_limits_avg_change = (last_pretrade_date.sum { |limit| JSON.parse($Redis.get(limit.ts_code[0..5]))["changepercent"].to_f } / last_pretrade_date.size).round(2) if last_pretrade_date.size != 0

    arr = Parallel.map(Stock.all, in_processes: 1, progress: false) do |stock|
      today = redis_stocks.find { |x| x["code"] == stock.symbol }
      stock if ((%w(0 6).include? stock.symbol[0]) && today["changepercent"].to_f > 9.9) || ((%w(0 6).include? stock.symbol[3]) && today["changepercent"].to_f > 19.9)
    end
    gn_base50_name = BlockFlow.where(cate_type: "N", mark: "base").last(50).pluck(:name)
    hy_base50_name = BlockFlow.where(cate_type: "I", mark: "base").last(50).pluck(:name)
    # 添加自定义内容块
    columns do
      column { panel "昨日涨停数量: #{last_pretrade_date.size}  最大连板数：#{yesterday_limit_time_max}" }
      column { panel "今日涨停数量：#{last_cal_date.size}   最大连板数：#{today_limit_time_max}   平均涨幅：#{all_limits_avg_change}" }
      column { panel "实时涨停数量: #{arr.compact.count}" }
      column { panel "R_TIME = #{redis_stocks.first["ticktime"]}  ------- 上一交易日期last_cal_date: #{last_pretrade_date.last&.trade_date}" }
    end
    # ================================================================================================================================================
    columns do
      column do
        panel "昨日涨停数量: #{last_pretrade_date.size} 日期：#{last_pretrade_date.first&.trade_date&.strftime("%m-%d")}【连板晋级少，不要打板】" do
          table_for last_pretrade_date.select { |limit| limit.limit_times > 1 }.sort_by { |x| x.limit_times }.reverse do
            column '【name】' do |limit|
              link_to "#{limit.name}", "https://stockpage.10jqka.com.cn/#{limit.ts_code[0..5]}/", target: '_blank', rel: "noopener noreferrer"
            end
            column :ts_code do |limit|
              link_to "#{limit.ts_code}", admin_stock_path(Stock.find_by_ts_code(limit.ts_code).id)
            end
            column :change do |limit|
              "#{redis_stocks.find { |x| x["code"] == limit.ts_code[0..5] }["changepercent"].to_f.round(2)}%" if redis_stocks.find { |x| x["code"] == limit.ts_code[0..5] }
            end
            column '连' do |limit|
              limit.limit_times
            end
            column 'flow' do |limit|
              link_to "#{limit.ths_flow}", "https://stockpage.10jqka.com.cn/#{limit.ts_code[0..5]}/funds/#funds_sszjlx", target: '_blank', rel: "noopener noreferrer"
            end
            column :score
            column '年' do |limit|
              limit.year_count
            end
            column :block do |limit|
              "#{Stock.find_by_ts_code(limit.ts_code).blocks.pluck(:name) & gn_base50_name}" + "#{Stock.find_by_ts_code(limit.ts_code).blocks.pluck(:name) & hy_base50_name}"
            end
            column do |limit|
              stock = Stock.find_by_ts_code(limit.ts_code)
              fluctuation = Fluctuation.find_by_code(stock.symbol)
              if fluctuation.present?
                fluctuation.title
              else
                "F:无"
              end
            end
          end
        end
        panel "昨日涨停数量: #{last_pretrade_date.size} 日期：#{last_pretrade_date.first&.trade_date&.strftime("%m-%d")}【连板晋级少，不要打板】" do
          table_for last_pretrade_date.select { |limit| limit.limit_times <= 1 }.sort_by { |x| x.limit_times }.reverse do
            column '【name】' do |limit|
              link_to "#{limit.name}", "https://stockpage.10jqka.com.cn/#{limit.ts_code[0..5]}/", target: '_blank', rel: "noopener noreferrer"
            end
            column :ts_code do |limit|
              link_to "#{limit.ts_code}", admin_stock_path(Stock.find_by_ts_code(limit.ts_code).id)
            end
            column :change do |limit|
              redis_stocks.find { |x| x["code"] == limit.ts_code[0..5] }["changepercent"]
            end
            column '连' do |limit|
              limit.limit_times
            end
            column 'flow' do |limit|
              link_to "#{limit.ths_flow}", "https://stockpage.10jqka.com.cn/#{limit.ts_code[0..5]}/funds/#funds_sszjlx", target: '_blank', rel: "noopener noreferrer"
            end
            column :score
            column '年' do |limit|
              limit.year_count
            end
            column :block do |limit|
              "#{Stock.find_by_ts_code(limit.ts_code).blocks.pluck(:name) & gn_base50_name}" + "#{Stock.find_by_ts_code(limit.ts_code).blocks.pluck(:name) & hy_base50_name}"
            end
          end
        end
      end
      column do
        panel "今日涨停数量：#{last_cal_date.size} 日期：#{last_cal_date.first&.trade_date&.strftime("%m-%d")}" do
          table_for last_cal_date.select { |limit| limit.limit_times > 1 }.sort_by { |x| x.limit_times }.reverse do
            column '【name】' do |limit|
              link_to "#{limit.name}", "https://stockpage.10jqka.com.cn/#{limit.ts_code[0..5]}/", target: '_blank', rel: "noopener noreferrer"
            end
            column :ts_code do |limit|
              link_to "#{limit.ts_code}", admin_stock_path(Stock.find_by_ts_code(limit.ts_code).id)
            end
            column :change do |limit|
              redis_stocks.find { |x| x["code"] == limit.ts_code[0..5] }["changepercent"]
            end
            column '连' do |limit|
              limit.limit_times
            end
            column '年' do |limit|
              limit.year_count
            end
            column :block do |limit|
              "#{Stock.find_by_ts_code(limit.ts_code).blocks.pluck(:name) & gn_base50_name}" + "#{Stock.find_by_ts_code(limit.ts_code).blocks.pluck(:name) & hy_base50_name}"
            end
          end
        end
        panel "今日涨停数量：#{last_cal_date.size} 日期：#{last_cal_date.first&.trade_date&.strftime("%m-%d")}" do
          table_for last_cal_date.select { |limit| limit.limit_times <= 1 }.sort_by { |x| x.limit_times }.reverse do
            column '【name】' do |limit|
              link_to "#{limit.name}", "https://stockpage.10jqka.com.cn/#{limit.ts_code[0..5]}/", target: '_blank', rel: "noopener noreferrer"
            end
            column :ts_code do |limit|
              link_to "#{limit.ts_code}", admin_stock_path(Stock.find_by_ts_code(limit.ts_code).id)
            end
            column :change do |limit|
              redis_stocks.find { |x| x["code"] == limit.ts_code[0..5] }["changepercent"]
            end
            column '连' do |limit|
              limit.limit_times
            end
            column '年' do |limit|
              limit.year_count
            end
            column :block do |limit|
              "#{Stock.find_by_ts_code(limit.ts_code).blocks.pluck(:name) & gn_base50_name}" + "#{Stock.find_by_ts_code(limit.ts_code).blocks.pluck(:name) & hy_base50_name}"
            end
          end
        end
      end if last_cal_date.size > 0
      column do
        panel "涨幅-1%～3%" do
          last_pretrade_date_upf1_3 = last_pretrade_date.select do |limit|
            stock = redis_stocks.find { |x| x["code"] == limit.ts_code[0..5] }
            if stock.nil?
              Robot.send_alert limit
            end
            next unless stock && stock["changepercent"] # 确保存在 changepercent 值

            changepercent = stock["changepercent"].to_f # 将字符串转换为浮点数
            changepercent > -1 && changepercent < 3
          end
          table_for last_pretrade_date_upf1_3.reverse do
            column '【name】' do |limit|
              link_to "#{limit.name}", "https://stockpage.10jqka.com.cn/#{limit.ts_code[0..5]}/", target: '_blank', rel: "noopener noreferrer"
            end
            column :ts_code do |limit|
              link_to "#{limit.ts_code}", admin_stock_path(Stock.find_by_ts_code(limit.ts_code).id)
            end
            column :change do |limit|
              redis_stocks.find { |x| x["code"] == limit.ts_code[0..5] }["changepercent"]
            end
            column :tor do |limit|
              redis_stocks.find { |x| x["code"] == limit.ts_code[0..5] }["turnoverratio"].round(1)
            end
            column '连' do |limit|
              limit.limit_times
            end
            column 'flow' do |limit|
              link_to "#{limit.ths_flow}", "https://stockpage.10jqka.com.cn/#{limit.ts_code[0..5]}/funds/#funds_sszjlx", target: '_blank', rel: "noopener noreferrer"
            end
            column :score
            column '年' do |limit|
              limit.year_count
            end
            column :block do |limit|
              "#{Stock.find_by_ts_code(limit.ts_code).blocks.pluck(:name) & gn_base50_name}" + "#{Stock.find_by_ts_code(limit.ts_code).blocks.pluck(:name) & hy_base50_name}"
            end
          end
        end
        panel "涨幅 > 5%" do
          last_pretrade_date_upf1_3 = last_pretrade_date.select do |limit|
            stock = redis_stocks.find { |x| x["code"] == limit.ts_code[0..5] }
            if stock.nil?
              Robot.send_alert limit
            end
            next unless stock && stock["changepercent"] # 确保存在 changepercent 值

            changepercent = stock["changepercent"].to_f # 将字符串转换为浮点数
            changepercent > 5
          end
          table_for last_pretrade_date_upf1_3.reverse do
            column '【name】' do |limit|
              link_to "#{limit.name}", "https://stockpage.10jqka.com.cn/#{limit.ts_code[0..5]}/", target: '_blank', rel: "noopener noreferrer"
            end
            column :ts_code do |limit|
              link_to "#{limit.ts_code}", admin_stock_path(Stock.find_by_ts_code(limit.ts_code).id)
            end
            column :change do |limit|
              redis_stocks.find { |x| x["code"] == limit.ts_code[0..5] }["changepercent"]
            end
            column :tor do |limit|
              redis_stocks.find { |x| x["code"] == limit.ts_code[0..5] }["turnoverratio"].round(1)
            end
            column '连' do |limit|
              limit.limit_times
            end
            column 'flow' do |limit|
              link_to "#{limit.ths_flow}", "https://stockpage.10jqka.com.cn/#{limit.ts_code[0..5]}/funds/#funds_sszjlx", target: '_blank', rel: "noopener noreferrer"
            end
            column :score
            column '年' do |limit|
              limit.year_count
            end
            column :block do |limit|
              "#{Stock.find_by_ts_code(limit.ts_code).blocks.pluck(:name) & gn_base50_name}" + "#{Stock.find_by_ts_code(limit.ts_code).blocks.pluck(:name) & hy_base50_name}"
            end
          end
        end
        panel "涨幅 < -3%" do
          last_pretrade_date_down_f3 = last_pretrade_date.select do |limit|
            stock = redis_stocks.find { |x| x["code"] == limit.ts_code[0..5] }
            if stock.nil?
              Robot.send_alert limit
            end
            next unless stock && stock["changepercent"] # 确保存在 changepercent 值

            changepercent = stock["changepercent"].to_f # 将字符串转换为浮点数
            changepercent < -3
          end
          table_for last_pretrade_date_down_f3.reverse do
            column '【name】' do |limit|
              link_to "#{limit.name}", "https://stockpage.10jqka.com.cn/#{limit.ts_code[0..5]}/", target: '_blank', rel: "noopener noreferrer"
            end
            column :ts_code do |limit|
              link_to "#{limit.ts_code}", admin_stock_path(Stock.find_by_ts_code(limit.ts_code).id)
            end
            column :change do |limit|
              redis_stocks.find { |x| x["code"] == limit.ts_code[0..5] }["changepercent"]
            end
            column :tor do |limit|
              redis_stocks.find { |x| x["code"] == limit.ts_code[0..5] }["turnoverratio"].round(1)
            end
            column '连' do |limit|
              limit.limit_times
            end
            column 'flow' do |limit|
              link_to "#{limit.ths_flow}", "https://stockpage.10jqka.com.cn/#{limit.ts_code[0..5]}/funds/#funds_sszjlx", target: '_blank', rel: "noopener noreferrer"
            end
            column :score
            column '年' do |limit|
              limit.year_count
            end
            column :block do |limit|
              "#{Stock.find_by_ts_code(limit.ts_code).blocks.pluck(:name) & gn_base50_name}" + "#{Stock.find_by_ts_code(limit.ts_code).blocks.pluck(:name) & hy_base50_name}"
            end
          end
        end
      end
    end
    8.times do |time|
      columns do
        (1..5).each do |i|
          date = trade_date(time * 5 + i)
          limit_lists = LimitList.where(created_at: Time.parse(date).beginning_of_day..Time.parse(date).end_of_day)
          records = limit_lists.select { |x| x.limit_times.to_f >= 3 }
          column do
            panel "#{date} 涨停数量：#{limit_lists.count} " do
              redis_stocks = Parallel.map(records, in_processes: 1, progress: false) do |stock|
                JSON.parse $Redis.get(stock.ts_code[0..5])
              end
              table_for records.reverse do
                column "股票名称" do |limit|
                  stock = Stock.find_by_name limit.name
                  stock.present? ? link_to("#{stock.name}", admin_stock_path(stock.id)) : "#{limit.name}"
                end
                column :次 do |limit|
                  limit.limit_times
                end
                column :幅 do |limit|
                  redis_stocks.find { |x| x["code"] == limit.ts_code[0..5] }["changepercent"].to_f.round(1)
                end
                column "title" do |limit|
                  stock = Stock.find_by_ts_code(limit.ts_code)
                  fluctuation = Fluctuation.where(code: stock.symbol, trend: "涨停").last
                  if fluctuation.present?
                    fluctuation.title.split("：")[1]
                  else
                    "F:无"
                  end
                end
              end
            end
          end
        end
      end
    end

    div class: "blank_slate_container" do
      span class: "blank_slate" do
        span "Welcome to Custom Dashboard"
        small "This is a custom admin page created with ActiveAdmin"
      end
    end
    script type: 'text/javascript' do
      "setInterval(function(){ window.location.reload(); }, 30000);".html_safe
    end
  end
end